import React, { Component } from 'react'
import {
  Layout,
  Drawer,
  Menu,
  Dropdown,
  Icon,
  message,
  Button,
  Avatar,
} from 'antd'
import 'antd/dist/antd.css'
import { BrowserRouter as Router, Route, HashRouter } from 'react-router-dom'
import axios from '../../rudexRou/urlHttp.js'
import {
  uncompileStr,
  VerifySessionTime,
  compileStrCop,
  findConfig,
  compileStr,
  getHeaderParams,
  getResponseUrl,
  getLinkToUrl,
  devProTest,
  frontUrlTest,
} from '../../rudexRou/OperatesCookie.js'
import routers from '../../rudexRou/routers.js'
import './SecondPages.css'
import { dataAxios } from '../../rudexRou/request.js'
import moment from 'moment'
import {
  SettingOutlined,
  SafetyCertificateOutlined,
  ProjectOutlined,
  UsergroupDeleteOutlined,
  CalendarOutlined,
  FolderOutlined,
  SolutionOutlined,
  ScanOutlined,
  DownOutlined,
  UserOutlined,
} from '@ant-design/icons'
message.config({
  top: 60,
})
moment.locale('zh-cn')
const { Header, Footer, Content, Sider } = Layout
const { SubMenu } = Menu

class Leftmenu extends Component {
  constructor(props) {
    super(props)
    this.state = {
      drawerVisible: false,
      current: '1',
      menuData: [],
      Leftmenus: null,
      isLeftMenuShow: this.props.isLeftMenuShow,
      OpenKey: [],
      // roleName: this.props.roleList && this.props.roleList.length > 0 ? this.props.roleList[0].roleName : "默认角色",
      // roleList: this.props.roleList && this.props.roleList.length > 0 ? this.props.roleList : [],
      // JudgeWhetherOrNotShowTable: []
    }
    this.userInfo = {}
    this.rootSubmenuKeys = []
  }
  componentWillMount() {}
  componentWillReceiveProps(nextprops) {
    if (nextprops.isLeftMenuShow != this.props.isLeftMenuShow) {
      this.setState({
        isLeftMenuShow: !this.state.isLeftMenuShow,
      })
    }
    let data = JSON.parse(localStorage.getItem('config'))
    let pathObj = getHeaderParams()
    this.getBreadcrumb(data, pathObj.menuId)
  }
  componentDidMount() {
    let pathObj = getHeaderParams()
    let data = JSON.parse(localStorage.getItem('config'))
    this.getBreadcrumb(data, pathObj.menuId)
  }

  //左侧菜单
  getBreadcrumb(data, id, type) {
    let _this = this,
      list = []

    data.map((item) => {
      // if (item.systemId == id) {
      //     list.push(item)
      // } else {
      //     item.services.map(its => _this.searchChildid(list, [item], its, id))
      // }
      //为了防止systemId与menuId 出现相同情况。所以暂不考虑systemId那一层，从属性services层开始循环
      item.services.map((its) => _this.searchChildid(list, [item], its, id))
    })
    this.setState({ Leftmenus: list }, () => {
      let key = []
      if (list && list.length > 0) {
        list.map((res) => {
          if (res.type === 0 && !res.routeId) {
            if (key.indexOf(res.menuId.toString()) === -1) {
              key.push(res.menuId.toString())
            }
          }
        })
        //设置左侧菜单目录Key 默认打开当前页面所在的目录
        this.setState({ OpenKey: key })
      }
    })
  }
  searchChildid(list, parentlist, its, id) {
    let _this = this
    if (its.type != 2) {
      if (its.menuId == id) {
        parentlist.push(its)
        parentlist.map((it) => list.push(it))
      } else {
        let arry = [...parentlist]
        arry.push(its)
        its.sonMenus &&
          its.sonMenus.map((it) => _this.searchChildid(list, arry, it, id))
      }
    }
  }

  getLinkURl(item) {
    let url = item.pointUrl != null ? item.pointUrl : item.url
    if (url.indexOf('MAG_PMIT') > -1) {
      //PMIT跳转
      let pwd = uncompileStr(localStorage.getItem('password'))
      let name = localStorage.getItem('userAccount')
      let penData = compileStr(
        JSON.stringify({
          password: pwd,
          remember: '0',
          username: name,
        })
      )
      window.open(
        getLinkToUrl('ipsa') + '/MAG_PMIT/new/#/?' + penData,
        '_blank'
      )
    } else if (url.indexOf('MAG_iHMS') > -1) {
      let pwd = localStorage.getItem('password')
      let name = localStorage.getItem('userAccount')
      item.url = item.url.replace('{name}', name)
      item.url = item.url.replace('{pwd}', pwd)
      window.open(getLinkToUrl('ipsa') + item.url)
    } else if (url.indexOf('MAG_SMARTSAFE') > -1) {
      //跳转至信息安全
      axios
        .get(
          getResponseUrl('ResponsePMITSystem') +
            '/rest/getIsmInfo/' +
            localStorage.getItem('userAccount')
        )
        .then((response) => {
          if (response.status === 200) {
            let roleId = response.data.data.role
            let username = encodeURIComponent(
              JSON.parse(localStorage.getItem('userInfo')).empName
            )
            let jobnumber = localStorage.getItem('empNo')
            let allPem =
              'userId=' +
              jobnumber +
              '&userName=' +
              username +
              '&roleId=' +
              roleId +
              '&password=' +
              localStorage.getItem('password') +
              '&userAccount=' +
              localStorage.getItem('userAccount')
            let codePem = encodeURIComponent(allPem)
            window.open(getLinkToUrl('ipsa') + url + '?' + codePem, '_blank')
          } else {
          }
        })
    } else if (url.indexOf('ICAN_SMARTSAFE') > -1) {
      //跳转至信息安全--RPC
      axios
        .get(
          getResponseUrl('ResponsePMITSystem') +
            '/rest/getIsmInfo/' +
            localStorage.getItem('userAccount')
        )
        .then((response) => {
          if (response.status === 200) {
            let roleId = response.data.data.role
            let username = encodeURIComponent(
              JSON.parse(localStorage.getItem('userInfo')).empName
            )
            let jobnumber = localStorage.getItem('empNo')
            let allPem =
              'userId=' +
              jobnumber +
              '&userName=' +
              username +
              '&roleId=' +
              roleId +
              '&password=' +
              localStorage.getItem('password') +
              '&userAccount=' +
              localStorage.getItem('userAccount')
            let codePem = encodeURIComponent(allPem)
            if (devProTest() === 'ipsa') {
              window.open(getLinkToUrl('ipsa') + url + '?' + codePem, '_blank')
            } else {
              window.open(
                'http://10.61.121.63:8080' + url + '?' + codePem,
                '_blank'
              )
            }
          } else {
          }
        })
    } else if (url.indexOf('MAGCOP') > -1) {
      let pwd = uncompileStr(localStorage.getItem('password'))
      let name = localStorage.getItem('userAccount')
      window.open(
        `${getLinkToUrl('ipsa')}${url}?userId=${name}&password=${compileStrCop(
          pwd
        )}`,
        '_blank'
      )
    } else {
      let menuId =
        item.pointId == -1 || item.pointId == undefined
          ? item.menuId
          : item.pointId //当前节点需要跳转页面的menuId
      let parentId =
        item.pointParentId == -1 || item.pointParentId == undefined
          ? item.parentId
          : item.pointParentId //当前节点需要跳转页面的parentId
      let realMenuId = item.menuId //点击当前节点的Id

      if (url.indexOf('MAG-ICAN') > -1) {
        //Ican自由工程
        let urls = url
        if (urls.indexOf('statistics/query') > -1) {
          let beginTime = moment()
            .startOf('day')
            .format('YYYY-MM-DD')
          let endTime = moment()
            .endOf('day')
            .format('YYYY-MM-DD')
          url = urls + `/${beginTime}/${endTime}`
        }
        if (devProTest() == 'develop') {
          window.location.href =
            frontUrlTest() +
            ':5002/#' +
            url +
            '/&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
        } else if (devProTest() == 'ipsa-test') {
          window.location.href =
            window.location.origin +
            '/iCan_Test/#' +
            url +
            '/&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
        } else if (devProTest() == '24') {
          window.location.href =
            window.location.origin +
            '/iCan/#' +
            url +
            '/&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
        } else if (devProTest() == 'ipsa') {
          window.location.href =
            window.location.origin +
            '/iCan/#' +
            url +
            '/&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
        }
      } else {
        //其他工程
        if (devProTest() === 'develop') {
          window.location.href =
            getLinkToUrl('platform') +
            url +
            '/&refreshToken=' +
            localStorage.getItem('refreshToken') +
            '&authToken=' +
            localStorage.getItem('authToken') +
            '&userAccount=' +
            localStorage.getItem('userAccount') +
            '&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
          //  window.open(getLinkToUrl('platform') + item + '/&refreshToken=' + localStorage.getItem("refreshToken") + "&authToken=" + localStorage.getItem("authToken") + '&userAccount=' + localStorage.getItem("userAccount"), '_blank');
        } else {
          window.location.href =
            getLinkToUrl('platform') +
            url +
            '/&menuId=' +
            menuId +
            '&parentId=' +
            parentId +
            '&systemId=' +
            item.systemId +
            '&realMenuId=' +
            realMenuId
          // window.open(getLinkToUrl('platform') + item, '_blank');
        }
      }
    }
  }
  setLeftMenu = () => {
    this.props.setLeftMenu()
  }
  handleMenuClick = (e) => {
    this.setState({ roleName: e.key })
    // console.log('click', e);
  }
  showSonMenus = (item) => {
    if (item.type != '2') {
      if (item.type === 0) {
        return (
          <SubMenu
            key={item.menuId}
            title={
              <span>
                <span>{item.name}</span>
              </span>
            }
          >
            {item.sonMenus && item.sonMenus.length > 0
              ? item.sonMenus.map((res) => {
                  return res.type === 0 &&
                    res.sonMenus &&
                    res.sonMenus.length > 0 ? (
                    this.showSonMenus(res)
                  ) : (
                    <Menu.Item
                      style={{ color: 'rgba(0,0,0,0.65)' }}
                      key={res.menuId}
                      onClick={() => this.getLinkURl(res)}
                    >
                      {res.name}
                    </Menu.Item>
                  )
                })
              : null}
          </SubMenu>
        )
      } else {
        return (
          <Menu.Item
            style={{ color: 'rgba(0,0,0,0.65)' }}
            key={item.menuId}
            onClick={() => this.getLinkURl(item)}
          >
            {item.name}
          </Menu.Item>
        )
      }
    }
  }
  onOpenChange = (openKeys) => {
    this.setState({ OpenKey: openKeys })
    // const latestOpenKey = openKeys.find(key => this.state.OpenKey.indexOf(key) === -1);
    // if (this.rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
    //     alert(22)
    //     this.setState({ OpenKey: openKeys });
    // } else {
    //     alert(11)
    //     this.setState({
    //         OpenKey: latestOpenKey ? [latestOpenKey] : [],
    //     });
    // }
  }
  render() {
    let Leftmenus = null
    if (this.state.Leftmenus && this.state.Leftmenus.length > 0) {
      this.state.Leftmenus.map((res) => {
        if (res.level + 1 === this.props.level - 1) {
          //左侧菜单展示this.props.level级以及this.props.level级以下的（也就是res.sonMenus）
          Leftmenus = res
        }
      })
    }
    let pathObj = getHeaderParams()

    return this.state.Leftmenus && Leftmenus && Leftmenus.sonMenus ? (
      <div
        style={{
          width:
            this.state.isLeftMenuShow && this.state.Leftmenus ? '208px' : null,
          float: 'left',
          position: 'relative',
          paddingTop: '24px',
          height: 'calc(100vh - 138px)',
        }}
      >
        {this.state.isLeftMenuShow && this.state.Leftmenus ? (
          <div className="leftMenus" style={{ overflow: 'auto' }}>
            <Menu
              //   defaultOpenKeys={[pathObj.realMenuId,pathObj.parentId]}
              openKeys={[...this.state.OpenKey]}
              selectedKeys={[pathObj.menuId]}
              onOpenChange={this.onOpenChange}
              mode="inline"
              style={{
                // height: this.state.roleList.length > 0 ? "calc(100vh - 178px)" : "calc(100vh - 138px)",
                height: 'calc(100vh - 138px)',
                // paddingTop: this.state.roleList.length > 0 ? 28 : 0,
                width: '208px',
              }}
            >
              {Leftmenus && Leftmenus.sonMenus.length > 0 ? (
                Leftmenus.type === 1 ? (
                  <Menu.Item
                    style={{ color: 'rgba(0,0,0,0.65)' }}
                    key={Leftmenus.menuId}
                    onClick={() => this.getLinkURl(Leftmenus)}
                  >
                    {Leftmenus.name}
                  </Menu.Item>
                ) : (
                  Leftmenus.sonMenus.map((item, index) => {
                    return this.showSonMenus(item)
                  })
                )
              ) : null}
            </Menu>
          </div>
        ) : null}

        <span
          className="collplaeSvg"
          style={{ right: this.state.isLeftMenuShow === true ? '-18px' : null }}
          onClick={this.setLeftMenu}
        ></span>
      </div>
    ) : null
  }
}
export default Leftmenu
